package com.lenovo.srl.dil.tiltbase.lib.sensor;

import java.util.Observable;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

import com.lenovo.srl.dil.tiltbase.lib.BaseApp;

/**
 * @author xieqd 传感器后台进程
 */
public class SensorsProcess extends Observable {

	private static final String TAG="SensorsProcess";
	private SensorManager mSensorManager;
	public float[] mOrientationOfRotationVector = new float[3];
	public float[] mOrientation = new float[3];

	public static float[] mR = new float[16];
	public static float[] mI = new float[16];
	public static float[] mOrientationCal = new float[3];

	public static float SENSOR_ACCELEROMETER[] = null;
	float SENSOR_MAGNETIC_FIELD[] = null;
	private static SensorsProcess instance = new SensorsProcess();

	private SensorsProcess() {
	}

	/**
	 * @return 传感器后台进程，以便获取传感器信息
	 */
	public static SensorsProcess getInstance() {
		return instance;
	}

	/**
	 * 启动传感器进程
	 */
	public void start() {
		registerSensor();
	}

	/**
	 * 停止传感器进程
	 */
	public void stop() {
		unRegisterSensor();
	}

	private void registerSensor() {
		Log.d(TAG, "registerSensor");
		registerState=true;
		mSensorManager = (SensorManager) BaseApp.getInstance()
				.getSystemService(Context.SENSOR_SERVICE);
		mSensorManager.registerListener(mSensorEventListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_GAME);
		mSensorManager.registerListener(mSensorEventListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
				SensorManager.SENSOR_DELAY_GAME);
	}

	public static boolean registerState=false;
	private void unRegisterSensor() {
		Log.d(TAG, "unRegisterSensor");
		if(mSensorManager!=null){
			mSensorManager.unregisterListener(mSensorEventListener);
		}
		registerState=false;
	}
	SensorEventListener mSensorEventListener = new SensorEventListener() {
		@SuppressLint("NewApi")
		@Override
		public void onSensorChanged(SensorEvent event) {

			if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
				SENSOR_ACCELEROMETER = event.values.clone();
			}
			if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
				SENSOR_MAGNETIC_FIELD = event.values.clone();
			}
			if (SENSOR_ACCELEROMETER != null && SENSOR_MAGNETIC_FIELD != null) {
				SensorManager.getRotationMatrix(mR, mI, SENSOR_ACCELEROMETER,
						SENSOR_MAGNETIC_FIELD);
				float[] orientation = new float[3];
				SensorManager.getOrientation(mR, orientation);
				orientation[0]=(float)Math.toDegrees(orientation[0]);
				orientation[1]=(float)Math.toDegrees(orientation[1]);
				orientation[2]=(float)Math.toDegrees(orientation[2]);
				
				setChanged();
				notifyObservers(orientation);
			}
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
		
	};
}
